package pers.wk.queues.work;

import com.rabbitmq.client.*;
import pers.wk.config.MQConfig;
import pers.wk.utils.MQConnectionUtils;

import java.text.MessageFormat;

/**
 * 工作队列-消费者
 * 公平队列，效率高的多消费
 */
public class Customer02 {

    private static String queueName = MQConfig.QueueNames.WORK_QUEUE_NAME;

    public static void main(String[] args) {
        //1.ConnectionFactory
        ConnectionFactory connectionFactory = MQConnectionUtils.getConnectionFactory("/");
        Connection connection = null;
        Channel channel = null;
        try {
            //2.创建连接
            connection = connectionFactory.newConnection();
            //3.通过连接获取通道Channel
            channel = connection.createChannel();

            channel.queueDeclare(queueName,
                    false, false, false, null);
            System.out.println("工作队列-消费者02，启动。。。");

            Channel channelTemp = channel;
            channelTemp.basicQos(1);
            channelTemp.basicConsume(queueName, false, (consumerTag, message) -> {
                //@FunctionalInterface DeliverCallback
                try {
                    System.out.println(MessageFormat.format("工作队列02-消费者获取消息：【{1}】{0}",
                            new String(message.getBody(), "UTF-8")
                            , message.getEnvelope().getDeliveryTag()));
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //手动应答
                    channelTemp.basicAck(message.getEnvelope().getDeliveryTag(), false);
                }
            }, (consumerTag) -> {
                //@FunctionalInterface CancelCallback
            });

            //
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MQConnectionUtils.close(connection, channel);
        }

    }
}
